import React from "react";
import "./Map.css";
import "leaflet/dist/leaflet.css";
import 'font-awesome/css/font-awesome.css';
import * as L from "leaflet"
import * as esri from "esri-leaflet";
import 'leaflet.locatecontrol';
import "leaflet.chinatmsproviders"
import CryptoJS from "crypto-js"


class Map extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            //地图组件
            map:null,
            //巡查员绘制层
            inspectorLayer:null,
            //管网地图服务URL
            pipeMapUrl:"http://111.30.67.228:6080/arcgis/rest/services/TJPIP/MapServer",
            //巡查员资料获取URL
            dateUrl:"http://111.30.67.228/api/GetOnlineInspector",
            //权限获取URL
            powerUrl:"http://111.30.67.228/api/GetMyDataPower",
            //登陆后返回的口令（单点登录口令）
            token:''
        };
    }

    render() {
        return (
            <div className="Map">
                <div id="l_map"></div>
            </div>
        );
    }

    componentDidMount() {
        this.initUser();
        this.initMap();
        var that = this;
        setInterval(() => {
            that.getInspectors();
        }, 1000*60*3);
        this.getInspectors();
    }

    initUser()
    {
        const secretKey = "fClzXg2oMRA\\="
        const userInfo = JSON.parse(window.localStorage.getItem("loginData"));
        if (userInfo != null) {
            const userAndPassword = userInfo.userName + "+" + userInfo.password;
            var hexKey = CryptoJS.enc.Base64.parse(secretKey);
            var des = CryptoJS.DES.encrypt(userAndPassword,hexKey, 
            {
                iv: hexKey,
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
            });
            this.state.token = des.ciphertext.toString().toUpperCase();
        }
    }

    initMap() {
        // 电子地图
        let vec_c_Layer = L.tileLayer.chinaProvider('TianDiTu.Normal.Map', { maxZoom: 18, minZoom: 0 });
        // 电子地图地图注记
        let cva_c_layer = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', { maxZoom: 18, minZoom: 0 });
        //影像图
        let img_c_Layer = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', { maxZoom: 18, minZoom: 0 });
        //影像图注记
        let cia_c_layer = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion', { maxZoom: 18, minZoom: 0 });

        let gray_layer = esri.tiledMapLayer({
            url:"http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetGray/MapServer",
        })

        let vec_layer = L.layerGroup([vec_c_Layer, cva_c_layer]),
            img_layer = L.layerGroup([img_c_Layer, cia_c_layer]);
        this.state.map = L.map("l_map", {
            crs: L.CRS.EPSG3857,
            center: [39.14, 117.21],
            zoom: 11,
            zoomControl: false,
            attributionControl: false
        });
        this.state.map.addLayer(vec_layer);
        //地图图层控件
        let baseLayers = {
            电子地图: vec_layer,
            影像地图: img_layer,
            灰度地图:gray_layer
        };
        L.control
            .layers(baseLayers, null, { position: "topright" })
            .addTo(this.state.map);
        //放大缩小控件
        L.control.zoom({ position: "bottomright" }).addTo(this.state.map);
        //定位控件
        L.control
            .locate({
                position: 'bottomleft',
                showCompass: true,
                enableHighAccuracy: true
            })
            .addTo(this.state.map).start();
        //管线图层
        this.initPipeData();
        //巡查员图层
        this.state.inspectorLayer = L.layerGroup([]).addTo(this.state.map);
    }

    //加载管线地图
    initPipeData(){
        fetch(this.state.powerUrl,{
            method:'POST',
            body:JSON.stringify({token:this.state.token}),
            headers: {
                'content-type': 'application/json'
            }
        }).then(response=>{
            if (response.status === 200) {
                response.json().then(result=>{
                    if (result.ErrorCode === 0) {
                        var powers = result.Data;
                        var sql = "权属单位='隐公元年' OR ";
                        for (var i = 0; i < powers.length; i++) {
                            sql += "权属单位='" + powers[i].DataName + "' OR ";
                        }
                        sql = sql.substr(0, sql.length - 4);
                        //对每个级别的数据都做处理
                        var layerIndexs = [1,2,3,4,5,6];
                        for (let index = 1; index < 7; index++) {
                            layerIndexs.push(layerIndexs[0 + (index -1) * 6] + 8);
                            layerIndexs.push(layerIndexs[1 + (index -1) * 6] + 8);
                            layerIndexs.push(layerIndexs[2 + (index -1) * 6] + 8);
                            layerIndexs.push(layerIndexs[3 + (index -1) * 6] + 8);
                            layerIndexs.push(layerIndexs[4 + (index -1) * 6] + 8);
                            layerIndexs.push(layerIndexs[5 + (index -1) * 6] + 8);
                        }
                        var defs = {};
                        for (let index = 0; index < layerIndexs.length; index++) {
                            defs[layerIndexs[index]] = sql; 
                        }
                        esri.dynamicMapLayer({
                            url: this.state.pipeMapUrl,
                            layers:layerIndexs,
                            layerDefs:defs
                        }).addTo(this.state.map);
                    }
                });
            }
        }).catch(error=>{
            console.error(error);
        });
    }
    

    //获取巡查员
    getInspectors(){
        this.state.inspectorLayer.clearLayers();
        fetch(this.state.dateUrl,{
            method:'POST',
            body:JSON.stringify({token:this.state.token}),
            headers: {
                'content-type': 'application/json'
            }
        }).then(response=>{
            if (response.status === 200) {
                response.json().then(result=>{
                    for (var i = 0; i < result.Data.length; i++) {
                        if (result.ErrorCode === 0) {
                            var points = result.Data[i].Points;
                            if (points.length > 0) {
                                var lastPoints = points[points.length - 1];
                                var inspectorIcon = L.icon({
                                    iconUrl: require('./assets/inspector.png'),
                                    iconSize: [32, 32],
                                    iconAnchor: [16, 32]
                                });
                                L.marker([lastPoints.Latitude, lastPoints.Longitude], {icon: inspectorIcon}).addTo(this.state.inspectorLayer);
                            }
                        }
                    }
                });
            }
        }).catch(error=>{
            console.error(error);
        });
    }
}

export default Map;
